package com.ayuku.commons;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;

import org.eclipse.nebula.widgets.grid.Grid;
import org.eclipse.nebula.widgets.grid.GridItem;
import org.eclipse.nebula.widgets.tablecombo.TableCombo;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TableItem;

import com.ayuku.commons.business.appgroup.AppGroupImpl;
import com.ayuku.commons.business.appmenu.AppMenuImpl;
import com.ayuku.commons.ui.usergroup.ListAppGroup;
import com.ayuku.commons.ui.users.ListUser;
import com.ayuku.retail.persistence.model.AppFunctions;
import com.ayuku.retail.persistence.model.AppGroup;
import com.ayuku.retail.persistence.model.AppUserGroupFunc;
import com.ayuku.retail.persistence.model.AppUsers;
import com.ayuku.retail.persistence.model.LoginLog;
import com.ayuku.retail.ui.category.ListCategory;
import com.ayuku.retail.ui.customers.ListCustomers;
import com.ayuku.retail.ui.kasir.SalesCash;
import com.ayuku.retail.ui.pembelian.ListPurchase;
import com.ayuku.retail.ui.stock.ListStock;
import com.ayuku.retail.ui.supplier.ListSupplier;

/**
 * 
 * @author putu kusuma <putukn@gmail.com>
 *
 */
public class Util {

	public static Shell SHELL;
	public static String PERIODE_ID;
	public static AppUsers currentUser;
	public static MathContext ROUND_1 = new MathContext(1);
	public static MathContext ROUND_2 = new MathContext(2);
	public static int OPERATION_CODE = 0;
	private static ListAppGroup listGroups;
	private static ListUser listUser;
	private static Locale locale = Locale.getDefault();

	public static Locale getLocale() {
		return locale;
	}

	public static void setLocale(Locale locale) {
		Util.locale = locale;
	}

	// 1 = mode add, 2 = mode edit
	public static final void createAssign(Grid tblAuth, Integer mode,
			String groupId) throws Exception {

		List<AppFunctions> lstAllMenu = AppMenuImpl.getAllFunctions("");

		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 1) {
				GridItem rootItem = new GridItem(tblAuth, SWT.NULL);
				rootItem.setText(0, "" + funct.getId());
				rootItem.setText(1, "" + funct.getName());

				if (mode == 1 && groupId != null) {

					AppUserGroupFunc h = getFunc(groupId, funct.getId());
					rootItem.setChecked(2,
							h.getAccessView().equals("true") ? true : false);
					rootItem.setChecked(3,
							h.getAccessAdd().equals("true") ? true : false);
					rootItem.setChecked(4,
							h.getAccessEdit().equals("true") ? true : false);
					rootItem.setChecked(5,
							h.getAccessDelete().equals("true") ? true : false);
				}

				createAuthLev2(lstAllMenu, rootItem, funct.getId(), mode,
						groupId);
			}
		}
	}

	private static AppUserGroupFunc getFunc(String groupId, String funcId)
			throws Exception {
		AppUserGroupFunc m = AppGroupImpl.getFunc(groupId, funcId);
		if (m == null) {
			m = new AppUserGroupFunc();
			m.setGroupId(groupId);
			m.setFuncId(funcId);
			m.setAccessAdd("false");
			m.setAccessEdit("false");
			m.setAccessView("false");
			m.setAccessDelete("false");
		}
		return m;
	}

	public static void populateCmbGroup(TableCombo combo) throws Exception {
		setCmbBasic(combo);
		List<AppGroup> modelList = AppGroupImpl.getList("%%");

		int total = (modelList == null ? 0 : modelList.size());
		combo.getTable().setItemCount(total + 1);

		TableItem ti = combo.getTable().getItem(0);
		ti.setText(new String[] { "", "" });

		for (int index = 0; index < total; index++) {
			ti = combo.getTable().getItem(index + 1);
			AppGroup model = modelList.get(index);
			ti.setText(new String[] { String.valueOf(model.getId()),
					model.getName() });
		}

	}

	private static void createAuthLev2(List<AppFunctions> lstAllMenu,
			GridItem itemRoot, String parentId, int mode, String groupId)
			throws Exception {

		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 2
					&& funct.getParentId().equalsIgnoreCase(parentId)) {

				GridItem item2 = new GridItem(itemRoot, SWT.NULL);
				item2.setText(0, "" + funct.getId());
				item2.setText(1, "" + funct.getName());

				if (mode == 1 && groupId != null) {

					AppUserGroupFunc h = getFunc(groupId, funct.getId());
					item2.setChecked(2, h.getAccessView().equals("true") ? true
							: false);
					item2.setChecked(3, h.getAccessAdd().equals("true") ? true
							: false);
					item2.setChecked(4, h.getAccessEdit().equals("true") ? true
							: false);
					item2.setChecked(5,
							h.getAccessDelete().equals("true") ? true : false);
				}

				createAuthLev3(lstAllMenu, item2, funct.getId(), mode, groupId);
			}
		}
	}

	private static void createAuthLev3(List<AppFunctions> lstAllMenu,
			GridItem item2, String parentId, int mode, String groupId)
			throws Exception {

		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 3
					&& funct.getParentId().equalsIgnoreCase(parentId)) {

				GridItem item3 = new GridItem(item2, SWT.NULL);
				item3.setText(0, "" + funct.getId());
				item3.setText(1, "" + funct.getName());
				if (mode == 1 && groupId != null) {

					AppUserGroupFunc h = getFunc(groupId, funct.getId());
					item3.setChecked(2, h.getAccessView().equals("true") ? true
							: false);
					item3.setChecked(3, h.getAccessAdd().equals("true") ? true
							: false);
					item3.setChecked(4, h.getAccessEdit().equals("true") ? true
							: false);
					item3.setChecked(5,
							h.getAccessDelete().equals("true") ? true : false);
				}

				createAuthLev4(lstAllMenu, item3, funct.getId(), mode, groupId);
			}
		}
	}

	private static void createAuthLev4(List<AppFunctions> lstAllMenu,
			GridItem item3, String parentId, int mode, String groupId)
			throws Exception {

		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 3
					&& funct.getParentId().equalsIgnoreCase(parentId)) {
				GridItem item4 = new GridItem(item3, SWT.NULL);
				item4.setText(0, "" + funct.getId());
				item4.setText(1, "" + funct.getName());

				if (mode == 1 && groupId != null) {

					AppUserGroupFunc h = getFunc(groupId, funct.getId());
					item4.setChecked(2, h.getAccessView().equals("true") ? true
							: false);
					item4.setChecked(3, h.getAccessAdd().equals("true") ? true
							: false);
					item4.setChecked(4, h.getAccessEdit().equals("true") ? true
							: false);
					item4.setChecked(5,
							h.getAccessDelete().equals("true") ? true : false);
				}
			}
		}
	}

	public static final void createMenu(Menu mnuBar, String userId)
			throws Exception {

		List<AppFunctions> lstAllMenu = AppMenuImpl.getAllMenu(userId);

		if (lstAllMenu == null) {
			throw new Exception(
					"Silakan Perbaiki dulu createMenu pada UTil.java");
		}

		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 1) {
				MenuItem mainMenu1 = new MenuItem(mnuBar, SWT.CASCADE);
				mainMenu1.setText(funct.getName());
				mainMenu1.setData("" + funct.getId());

				mainMenu1.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						doAction(evt);
					}
				});
				createMenuLevel2(lstAllMenu, mainMenu1);
			}
		}
	}

	private static void createMenuLevel2(List<AppFunctions> lstAllMenu,
			MenuItem mnuParent) {
		Menu mnuSubLevel2 = new Menu(mnuParent);

		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 2
					&& funct.getParentId().equalsIgnoreCase(
							mnuParent.getData().toString())) {
				mnuParent.setMenu(mnuSubLevel2);
				MenuItem menuLevel2 = new MenuItem(mnuSubLevel2, SWT.CASCADE);
				menuLevel2.setText(funct.getName());
				menuLevel2.setData("" + funct.getId());
				menuLevel2.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						doAction(evt);
					}
				});
				createMenuLevel3(lstAllMenu, menuLevel2);
			}
		}
	}

	private static void createMenuLevel3(List<AppFunctions> lstAllMenu,
			MenuItem mnuParent) {
		Menu mnuSubLevel3 = new Menu(mnuParent);
		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 3
					&& funct.getParentId().equalsIgnoreCase(
							mnuParent.getData().toString())) {
				mnuParent.setMenu(mnuSubLevel3);
				MenuItem menuLevel3 = new MenuItem(mnuSubLevel3, SWT.CASCADE);
				menuLevel3.setText(funct.getName());
				menuLevel3.setData("" + funct.getId());
				menuLevel3.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						doAction(evt);
					}
				});
				createMenuLevel4(lstAllMenu, menuLevel3);
			}
		}
	}

	private static void createMenuLevel4(List<AppFunctions> lstAllMenu,
			MenuItem mnuParent) {
		Menu mnuSubLevel4 = new Menu(mnuParent);
		for (int i = 0; i < lstAllMenu.size(); i++) {
			AppFunctions funct = (AppFunctions) lstAllMenu.get(i);
			if (funct.getDepth() == 4
					&& funct.getParentId().equalsIgnoreCase(
							mnuParent.getData().toString())) {
				mnuParent.setMenu(mnuSubLevel4);
				MenuItem menuLevel3 = new MenuItem(mnuSubLevel4, SWT.CASCADE);
				menuLevel3.setText(funct.getName());
				menuLevel3.setData("" + funct.getId());
				menuLevel3.addSelectionListener(new SelectionAdapter() {
					public void widgetSelected(SelectionEvent evt) {
						doAction(evt);
					}
				});
			}
		}
	}

	public static boolean isAllowedAdd(String funcId) {
		AppUsers user = Util.getCurrentUser();
		String groupId = user.getGroupId();
		boolean isAllowed = false;
		try {
			isAllowed = (Boolean) AppGroupImpl.getAllowedAdd(groupId, funcId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isAllowed;
	}

	public static boolean isAllowedView(String funcId) {
		AppUsers user = Util.getCurrentUser();
		String groupId = user.getGroupId();
		boolean isAllowed = false;
		try {
			isAllowed = AppGroupImpl.getAllowedView(groupId, funcId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isAllowed;
	}

	public static boolean isAllowedEdit(String funcId) {
		AppUsers user = Util.getCurrentUser();
		String groupId = user.getGroupId();
		boolean isAllowed = false;
		try {
			isAllowed = AppGroupImpl.getAllowedEdit(groupId, funcId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isAllowed;
	}

	public static boolean isAllowedDelete(String funcId) {
		AppUsers user = Util.getCurrentUser();
		String groupId = user.getGroupId();
		boolean isAllowed = false;
		try {
			isAllowed = AppGroupImpl.getAllowedDelete(groupId, funcId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isAllowed;
	}

	private static ListCustomers listCustomers;
	private static ListPurchase listPurchase;
	private static ListStock listStock;
	private static ListSupplier listSupplier;
	private static ListCategory listCategory;
	private static SalesCash salesCash;

	private static void doAction(SelectionEvent evt) {
		String funcId = ((MenuItem) evt.getSource()).getData().toString();

		if (funcId.equals("list_group")) {
			listGroups = new ListAppGroup(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			listGroups.setFuncId(funcId);
			listGroups.open();
		}

		if (funcId.equals("list_category")) {
			listCategory = new ListCategory(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			listCategory.setFuncId(funcId);
			listCategory.open();
		}

		if (funcId.equals("list_user")) {
			listUser = new ListUser(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			listUser.setFuncId(funcId);
			listUser.open();
		}

		if (funcId.equals("list_customer")) {
			listCustomers = new ListCustomers(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			listCustomers.setFuncId(funcId);
			listCustomers.open();
		}

		if (funcId.equals("add_purchase")) {
			listPurchase = new ListPurchase(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			listPurchase.setFuncId(funcId);
			listPurchase.open();
		}

		if (funcId.equals("list_stock")) {
			listStock = new ListStock(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			listStock.setFuncId(funcId);
			listStock.open();
		}

		if (funcId.equals("list_supplier")) {
			listSupplier = new ListSupplier(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			listSupplier.setFuncId(funcId);
			listSupplier.open();
		}

		if (funcId.equals("sales_cash")) {
			try {
				AyukuDB.getPersist().executeUpdate(
						"TRUNCATE TABLE trx_temp_sale");

			} catch (SQLException e) {
				e.printStackTrace();
			}

			salesCash = new SalesCash(Util.SHELL, SWT.RESIZE
					| SWT.APPLICATION_MODAL);
			salesCash.setFuncId(funcId);
			salesCash.open();
		}

	}

	public static final AppUsers getCurrentUser() {
		return currentUser;
	}

	public static final void setCurrentUser(AppUsers currentUser) {
		Util.currentUser = currentUser;
	}

	public static void showMsgBox(final String msg, final int jns,
			final Shell dialogShell) {
		MessageBox message = new MessageBox(dialogShell, SWT.OK
				| SWT.ICON_INFORMATION);
		if (jns == 1) {
			message = new MessageBox(dialogShell, SWT.OK | SWT.ICON_WARNING);
		} else if (jns == 2) {
			message = new MessageBox(dialogShell, SWT.OK | SWT.ICON_ERROR);
		}
		message.setText(AYConst.APP_TITLE);
		message.setMessage(msg);
		message.open();
	}

	public static String cleanStr(String str) {
		if (str != null) {
			str.replace("'", "");
		}
		return str.trim();
	}

	public static String nullToString(String str) {
		return (str == null) ? "" : str.trim();
	}

	public static String nullToString(Object obj) {
		return (obj == null) ? "" : String.valueOf(obj).trim();
	}

	public static Object nullToNumber(final Object obj) {
		return (obj == null) ? "0.00" : obj;
	}

	public static BigDecimal nullToBigDecimal(final Object obj) {
		return (obj == null) ? new BigDecimal(0.00) : (BigDecimal) obj;
	}

	public static Double nullToDouble(final Object obj) {
		return (obj == null) ? new Double(0.00) : (Double) obj;
	}

	public static Integer nullToInteger(final Object obj) {
		return (obj == null) ? new Integer("0") : Integer.valueOf(obj
				.toString());
	}

	public static Date nullToDate(final Date obj) {
		Date d = null;
		if (obj == null) {
			try {
				d = AYConst.TIMESTAMP_FORMAT.parse("1900-01-01 00:00:00");
				return d;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return obj;
	}

	public static Date getDefaultDate() {
		Date d = null;

		try {
			d = AYConst.TIMESTAMP_FORMAT.parse("1900-01-01 00:00:00");
			return d;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return d;
	}

	public static boolean isEmpty(final String str) {
		boolean rtrn = false;

		if ((str == null) || str.trim().equals("")) {
			rtrn = true;
		}

		return rtrn;
	}

	public static void doGarbage() {
		final Runtime runti = Runtime.getRuntime();
		runti.gc();
	}

	public static String dateToString(Date arg) {

		if (arg == null) {
			return "";
		}

		Calendar cal = new GregorianCalendar();
		cal.setTime(arg);
		cal.set(Calendar.YEAR, 1900);
		cal.set(Calendar.DATE, 1);
		cal.set(Calendar.MONTH, 0);

		try {
			if (arg.equals(cal.getTime())) {
				return "";
			} else {
				return AYConst.TANGGAL_FORM.format(arg);
			}
		} catch (Exception e) {
			return "";
		}
	}

	public static Calendar getCalendarFromDateTime(DateTime dt) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, dt.getDay());
		cal.set(Calendar.MONTH, dt.getMonth());
		cal.set(Calendar.YEAR, dt.getYear());
		cal.set(Calendar.HOUR_OF_DAY, dt.getHours());
		cal.set(Calendar.MINUTE, dt.getMinutes());
		cal.set(Calendar.SECOND, dt.getSeconds());

		return cal;
	}

	public static Calendar getCalendarFromSetting(DateTime dt) {
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, dt.getDay());
		cal.set(Calendar.MONTH, dt.getMonth());
		cal.set(Calendar.YEAR, dt.getYear());
		cal.set(Calendar.HOUR_OF_DAY, dt.getHours());
		cal.set(Calendar.MINUTE, dt.getMinutes());
		cal.set(Calendar.SECOND, dt.getSeconds());
		return cal;
	}

	public static void setDateTimeWithCalendar(Calendar cal, DateTime dt) {

		dt.setHours(cal.get(Calendar.HOUR));
		dt.setMinutes(cal.get(Calendar.MINUTE));
		dt.setSeconds(cal.get(Calendar.SECOND));
		dt.setYear(cal.get(Calendar.YEAR));
		dt.setMonth(cal.get(Calendar.MONTH));
		dt.setDay(cal.get(Calendar.DATE));

	}

	public static void setDateTimeWithDate(Date date, DateTime dt) {
		if (date == null) {
			return;
		}

		Calendar cal = Calendar.getInstance();
		cal.setTime(date);

		dt.setDay(cal.get(Calendar.DAY_OF_MONTH));
		dt.setMonth(cal.get(Calendar.MONTH));
		dt.setYear(cal.get(Calendar.YEAR));

		dt.setHours(cal.get(Calendar.HOUR_OF_DAY));
		dt.setMinutes(cal.get(Calendar.MINUTE));
		dt.setSeconds(cal.get(Calendar.SECOND));

	}

	public static long getDaysBtwTwoDate(Calendar start, Calendar end) {
		// Calculate difference in milliseconds
		long diff = end.getTimeInMillis() - start.getTimeInMillis();

		// Calculate difference in seconds
		// long diffSeconds = diff / 1000;

		// Calculate difference in minutes
		// long diffMinutes = diff / (60 * 1000);

		// Calculate difference in hours
		// long diffHours = diff / (60 * 60 * 1000);

		// Calculate difference in days
		// long diffDays = diff / (24 * 60 * 60 * 1000);

		return diff / (24 * 60 * 60 * 1000);
	}

	public static String dateTimeToString(DateTime dt) {
		return dt.getYear() + "-" + dt.getMonth() + "-" + dt.getDay();
	}

	public static String getShortDateTime(DateTime dt) {
		String strHour = dt.getHours() + "";
		String strMinute = dt.getMinutes() + "";

		if (strHour.length() < 2) {
			strHour = "0" + strHour;
		}
		if (strMinute.length() < 2) {
			strMinute = "0" + strMinute;
		}

		return strHour + ":" + strMinute;
	}

	public static String getAutoNoBukti() {
		Calendar cal = Calendar.getInstance();
		String tgl = cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH)
				+ cal.get(Calendar.DATE) + cal.get(Calendar.HOUR)
				+ cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND) + "";
		return tgl;
	}

	public static Integer strToInt(String arg) {
		if (arg == null || "".equals(arg.trim())) {
			return null;
		}
		int in = 0;
		try {
			in = Integer.parseInt(arg.trim());
		} catch (Exception e) {

		}
		return Integer.valueOf(in);
	}

	public static BigDecimal strToBigDecimal(String arg) {
		Number number = null;
		if (arg == null || "".equals(arg.trim())) {
			return null;
		} else {
			/*
			 * Pattern p = Pattern.compile("([0-9]*)\\.([0-9]*)"); Matcher m =
			 * p.matcher(arg.trim()); if (m.matches()) { return new
			 * BigDecimal(arg.trim()); } else { return null; }
			 */

			try {
				number = NumberFormat.getNumberInstance(getLocale()).parse(arg);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			System.out.println("Number in string: " + arg.trim());
			return BigDecimal.valueOf(Double.valueOf(number.toString()));
		}
	}

	public static Double strToDouble(String arg) {
		if (arg == null || "".equals(arg.trim())) {
			return null;
		} else {
			return Double.valueOf(arg.trim());
		}
	}

	public static void setCenter(Shell shell) {
		Monitor primary = shell.getDisplay().getPrimaryMonitor();
		Rectangle bounds = primary.getBounds();
		Rectangle rect = shell.getBounds();
		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;
		shell.setLocation(x, y);
	}

	public static void setSize(Shell shell, int x, int y) {
		shell.setSize(x, y);
	}

	public static void setFull(Shell shell) {
		Monitor primary = shell.getDisplay().getPrimaryMonitor();
		Rectangle bounds = primary.getBounds();
		shell.getBounds();
		/*
		 * int x = bounds.x + (bounds.width - rect.width) / 2; int y = bounds.y
		 * + (bounds.height - rect.height) / 2;
		 */
		shell.setLocation(0, 0);
		shell.setSize(bounds.width, bounds.height - 30);
	}

	private static void setCmbBasic(TableCombo combo) {
		// combo.getTable().removeAll();
		combo.defineColumns(new String[] { "kode", "nama" }, new int[] {
				SWT.DEFAULT, SWT.DEFAULT });
		combo.setDisplayColumnIndex(0);
		// turn on the table header.
		combo.setShowTableHeader(true);
		combo.setVisibleItemCount(40);
	}

	// get id from combo
	public static String getIdFromCmb(String strGrp) {
		String strId = null;
		if (strGrp != null) {
			int idx = strGrp.trim().indexOf("(");
			System.out.println("Index Of (: " + idx);
			if (!(idx < 0)) {
				strId = strGrp.substring((idx + 1),
						(strGrp.trim().length() - 1));
			}
			System.out.println("Grp: " + strId);
		}
		return strId;
	}

	// set combo selected
	public static void setCmbSelected(Combo cmb, String comp) {
		for (int i = 0; i < cmb.getItemCount(); i++) {
			System.out.println("item " + i + " " + cmb.getItem(i));
			String item = cmb.getItem(i);

			int idx = item.trim().indexOf("(");
			System.out.println("Index Of (: " + idx);
			String group = item
					.substring((idx + 1), (item.trim().length() - 1));
			System.out.println("Grp: " + group);
			if (group.equals(comp.toString())) {
			}

		}
	}

	public static BigDecimal getDecFromString(String strDec) {

		BigDecimal dc = new BigDecimal(0);
		try {
			dc = new BigDecimal(strDec);
		} catch (Exception e) {
			dc = new BigDecimal(0);
		}
		return dc;
	}

	public static Integer getIntFromString(String strDec) {
		Integer n = 0;
		try {
			n = new Integer(strDec);
		} catch (Exception e) {
			n = 0;
		}
		return n;
	}

	public static Date getDateFromStr(String strTgllahir) {
		Date birthDate = null;
		try {
			birthDate = AYConst.TANGGAL_EXCEL.parse(strTgllahir);
		} catch (ParseException e) {
		}
		return birthDate;
	}

	public static String formatToNumber(BigDecimal dec) {
		if (dec == null) {
			return "0";
		}
		return NumberFormat.getNumberInstance(getLocale()).format(dec);

	}

	public static String formatToNumber(Object value) {
		if (value == null) {
			return "0";
		}

		BigDecimal ret = null;
		if (value != null) {
			if (value instanceof BigDecimal) {
				ret = (BigDecimal) value;
			} else if (value instanceof String) {
				ret = new BigDecimal((String) value);
			} else if (value instanceof BigInteger) {
				ret = new BigDecimal((BigInteger) value);
			} else if (value instanceof Number) {
				ret = new BigDecimal(((Number) value).doubleValue());
			} else {
				throw new ClassCastException("Not possible to coerce [" + value
						+ "] from class " + value.getClass()
						+ " into a BigDecimal.");
			}
		}

		// Format for CANADA locale
		Locale locale = Locale.getDefault();
		NumberFormat.getNumberInstance(locale).format(-1234.56); // -1,234.56

		// Format for GERMAN locale
		locale = Locale.GERMAN;
		NumberFormat.getNumberInstance(locale).format(-1234.56); // -1.234,56

		// Format for the default locale
		NumberFormat.getNumberInstance().format(-1234.56);

		// Parse a GERMAN number
		try {
			Number number = NumberFormat.getNumberInstance(Locale.GERMAN)
					.parse("-1.234,56");
			if (number instanceof Long) {
				// Long value
			} else {
				// Double value
			}
		} catch (ParseException e) {
		}

		return NumberFormat.getNumberInstance(getLocale()).format(ret);

	}

	public static String formatToNumber(Double dec) {
		if (dec == null) {
			return "0";
		}
		NumberFormat formatter = new DecimalFormat(
				"###,###,###,###.##;(###,###,###,###.##)");
		return formatter.format(dec);

	}

	public static String getIPAddress() {
		String ipAddress = null;
		try {
			java.net.InetAddress inet = java.net.InetAddress.getLocalHost();
			ipAddress = inet.getHostAddress() + "";
		} catch (Exception e) {

		}
		return ipAddress;
	}

	public static LoginLog setLoginLog(String desc) {
		LoginLog lg = new LoginLog();
		lg.setUserName(getCurrentUser().getUname());
		lg.setFromIp(getIPAddress());
		lg.setDoDesc(desc);
		// lg.setFromMcAddress(Util.getMotherboardSN());
		lg.setFromMcAddress("--");
		lg.setDoDate(Calendar.getInstance().getTime());
		return lg;
	}

	public static Date getCurrentDate() {
		java.util.Date dt = null;
		try {
			dt = AyukuDB.getPersist().read(java.util.Date.class,
					"select CURRENT_TIMESTAMP()");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return dt;
	}

	public static String getSerialNumber(String drive) {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);

			String vbs = "Set objFSO = CreateObject(\"Scripting.FileSystemObject\")\n"
					+ "Set colDrives = objFSO.Drives\n"
					+ "Set objDrive = colDrives.item(\""
					+ drive
					+ "\")\n"
					+ "Wscript.Echo objDrive.SerialNumber"; // see note
			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.trim();
	}

	public static String getMotherboardSN() {
		String result = "";
		try {
			File file = File.createTempFile("realhowto", ".vbs");
			file.deleteOnExit();
			FileWriter fw = new java.io.FileWriter(file);

			String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
					+ "Set colItems = objWMIService.ExecQuery _ \n"
					+ "   (\"Select * from Win32_BaseBoard\") \n"
					+ "For Each objItem in colItems \n"
					+ "    Wscript.Echo objItem.SerialNumber \n"
					+ "    exit for  ' do the first cpu only! \n" + "Next \n";

			fw.write(vbs);
			fw.close();
			Process p = Runtime.getRuntime().exec(
					"cscript //NoLogo " + file.getPath());
			BufferedReader input = new BufferedReader(new InputStreamReader(
					p.getInputStream()));
			String line;
			while ((line = input.readLine()) != null) {
				result += line;
			}
			input.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.trim();
	}

	public static void main(String[] args) {
		String sn = Util.getSerialNumber("C");
		String snm = Util.getMotherboardSN();
		System.out.println("Serial Motherboard:" + snm);
		System.out.println("Serial Number of C:" + sn);

		String str1 = "33,876.52";
		String str2 = "-56,876.52";

		// To convert s String to a BigDecimal
		BigDecimal bigDecimal1 = new BigDecimal(str1);
		System.out.println("bigDecimal1 = " + bigDecimal1);

		// To convert s String to a BigDecimal
		BigDecimal bigDecimal2 = new BigDecimal(str2);
		System.out.println("bigDecimal2 = " + bigDecimal2);
	}

}
